<script setup lang="ts">
import { ref, computed } from 'vue' // 确保导入了computed
import * as exifr from 'exifr'

defineOptions({
  name: 'DevMinio'
})

const upload = ref<HTMLInputElement>()
const fileInfo = ref({
  name: '',
  type: '',
  size: 0,
  lastModified: '',
  imageWidth: 0,
  imageHeight: 0,
  hasExif: false,
  exifData: null as any,
  hasError: false,
  errorMessage: ''
})

// 处理文件变更的函数
// 添加计算属性来格式化GPS坐标
const formattedGPSInfo = computed(() => {
  if (!fileInfo.value.exifData) return null
  
  const { GPSLatitude, GPSLatitudeRef, GPSLongitude, GPSLongitudeRef, latitude, longitude } = fileInfo.value.exifData
  
  // 优先使用已经转换好的十进制坐标
  if (typeof latitude === 'number' && typeof longitude === 'number') {
    return {
      latitude: `${latitude.toFixed(6)}${GPSLatitudeRef || ''}`,
      longitude: `${longitude.toFixed(6)}${GPSLongitudeRef || ''}`
    }
  }
  
  // 如果没有现成的十进制坐标，则手动转换DMS格式
  if (Array.isArray(GPSLatitude) && Array.isArray(GPSLongitude)) {
    return {
      latitude: `${dmsToDecimal(GPSLatitude).toFixed(6)}${GPSLatitudeRef || ''}`,
      longitude: `${dmsToDecimal(GPSLongitude).toFixed(6)}${GPSLongitudeRef || ''}`
    }
  }
  
  return null
})

// 辅助函数：将DMS格式（度分秒）转换为十进制
function dmsToDecimal(dms: any[]): number {
  if (!Array.isArray(dms) || dms.length < 3) return 0
  
  const degrees = parseFloat(dms[0])
  const minutes = parseFloat(dms[1])
  const seconds = parseFloat(dms[2])
  
  return degrees + minutes / 60 + seconds / 3600
}

// 修改handleFileChange函数，确保数据被正确保存
const handleFileChange = async (event: Event) => {
  console.log('=== 开始处理文件变更事件 ===')

  try {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]

    if (!file) {
      console.log('未选择文件')
      fileInfo.value = {
        name: '',
        type: '',
        size: 0,
        lastModified: '',
        imageWidth: 0,
        imageHeight: 0,
        hasExif: false,
        exifData: null,
        hasError: false,
        errorMessage: ''
      }
      return
    }

    // 重置错误状态
    fileInfo.value.hasError = false
    fileInfo.value.errorMessage = ''

    // 设置文件基本信息
    fileInfo.value.name = file.name
    fileInfo.value.type = file.type
    fileInfo.value.size = file.size

    // 格式化最后修改时间
    const lastModifiedDate = new Date(file.lastModified)
    fileInfo.value.lastModified = lastModifiedDate.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })

    console.log('文件名:', file.name)
    console.log('文件类型:', file.type)
    console.log('文件大小:', file.size, 'bytes')

    if (!file.type.match('image.*')) {
      console.log('选择的不是图片文件')
      fileInfo.value.hasError = true
      fileInfo.value.errorMessage = '请选择图片文件'
      return
    }

    // 使用exifr解析EXIF数据
    console.log('开始读取并解析EXIF数据...')
    try {
      const exifData = await exifr.parse(file)
      console.log('EXIF数据解析成功:', exifData)
      // 添加GPS数据的详细日志
      console.log('GPS数据:', {
        GPSLatitude: exifData.GPSLatitude,
        GPSLongitude: exifData.GPSLongitude,
        GPSLatitudeRef: exifData.GPSLatitudeRef,
        GPSLongitudeRef: exifData.GPSLongitudeRef,
        // 检查是否有其他可能包含GPS信息的字段
        gps: exifData.gps,
        latitude: exifData.latitude,
        longitude: exifData.longitude
      })

      // 保存EXIF数据
      fileInfo.value.hasExif = !!exifData
      fileInfo.value.exifData = exifData

      // 获取图片尺寸
      if (exifData) {
        fileInfo.value.imageWidth = exifData.ImageWidth || 0
        fileInfo.value.imageHeight = exifData.ImageHeight || 0
      }

      // 如果没有通过EXIF获取到尺寸，创建图片对象获取
      if (!fileInfo.value.imageWidth) {
        const img = new Image()
        img.src = URL.createObjectURL(file)

        await new Promise((resolve, reject) => {
          img.onload = resolve
          img.onerror = reject
        })

        fileInfo.value.imageWidth = img.width
        fileInfo.value.imageHeight = img.height
        URL.revokeObjectURL(img.src)
      }
    } catch (exifError) {
      console.error('EXIF数据解析错误:', exifError)
      fileInfo.value.hasError = true
      fileInfo.value.errorMessage = 'EXIF数据解析错误'
    }
  } catch (error) {
    console.error('处理文件变更时发生错误:', error)
    fileInfo.value.hasError = true
    fileInfo.value.errorMessage = '处理文件时发生错误'
  }

  console.log('=== 文件变更事件处理完成 ===')
}
</script>

<template>
  <el-card class="icon-card">
    <input type="file" :ref="upload" name="image" accept="image/*" @change="handleFileChange" />

    <div
      v-if="fileInfo.name"
      class="file-info"
      style="margin-top: 15px; padding: 10px; background: #f5f5f5; border-radius: 4px"
    >
      <h4 style="margin: 0 0 10px 0; color: #333">文件信息</h4>
      <div v-if="fileInfo.hasError" style="color: red; margin-bottom: 10px">
        {{ fileInfo.errorMessage }}
      </div>
      <div class="info-item"><strong>文件名：</strong>{{ fileInfo.name }}</div>
      <div class="info-item"><strong>文件类型：</strong>{{ fileInfo.type }}</div>
      <div class="info-item">
        <strong>文件大小：</strong>{{ (fileInfo.size / 1024).toFixed(2) }} KB
      </div>
      <div class="info-item"><strong>最后修改：</strong>{{ fileInfo.lastModified }}</div>
      <div class="info-item">
        <strong>图片尺寸：</strong>{{ fileInfo.imageWidth }} x {{ fileInfo.imageHeight }}
      </div>

      <div
        v-if="fileInfo.hasExif"
        class="exif-info"
        style="margin-top: 10px; padding-top: 10px; border-top: 1px solid #ddd"
      >
        <h5 style="margin: 0 0 8px 0; color: #555">EXIF信息</h5>
        <div v-if="fileInfo.exifData.Make || fileInfo.exifData.Model" class="info-item">
          <strong>相机：</strong>{{ fileInfo.exifData.Make }} {{ fileInfo.exifData.Model }}
        </div>
        <div v-if="fileInfo.exifData.DateTimeOriginal" class="info-item">
          <strong>拍摄时间：</strong>{{ fileInfo.exifData.DateTimeOriginal }}
        </div>
        <div v-if="formattedGPSInfo" class="info-item">
          <strong>拍摄地点：</strong>
          {{ formattedGPSInfo.latitude }}, {{ formattedGPSInfo.longitude }}
        </div>
        <div v-if="fileInfo.exifData.FNumber" class="info-item">
          <strong>光圈：</strong>f/{{ fileInfo.exifData.FNumber }}
        </div>
        <div v-if="fileInfo.exifData.ExposureTime" class="info-item">
          <strong>快门：</strong>{{ fileInfo.exifData.ExposureTime }}s
        </div>
        <div v-if="fileInfo.exifData.ISO" class="info-item">
          <strong>ISO：</strong>{{ fileInfo.exifData.ISO }}
        </div>
      </div>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.file-info {
  .info-item {
    margin-bottom: 5px;
    line-height: 1.5;
  }

  .exif-info {
    .info-item {
      font-size: 13px;
    }
  }
}
</style>
